//
//  GeRenXinXiVC.m
//  EnterpriseEdition
//
//  Created by ypj on 2021/10/9.
//

#import "GeRenXinXiVC.h"
#import "TouXiangTableViewCell.h"
#import "CitiesListView.h"
#import "BRAddressPickerView.h"
@interface GeRenXinXiVC ()<UITableViewDelegate,UITableViewDataSource>

@property (nonatomic, strong) UITableView       *tableView;
@property (nonatomic, strong) NSMutableArray    *dataAry;
@property (nonatomic, strong) YLUserInfo        *info;
@property (nonatomic, strong) NSString             *userName;
@property (nonatomic, strong) NSString             *carNum;
@property (nonatomic, strong) NSString             *workAddress;
@property (nonatomic, strong) NSString             *avatar;
@property (nonatomic, strong) NSString *workAddressStr;
@property (nonatomic, strong) BRAddressPickerView *addressPickerView;
@end

@implementation GeRenXinXiVC

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
  
   
    [self refrefhUI];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = White_Color;
    [self layoutCustomNav:self.view title:@"个人信息"];
    [self createRightButtonItem];
    self.dataAry = [NSMutableArray arrayWithArray:@[@"头像",@"真实姓名",@"身份证号",@"工作地点"]];
    [self createTableView];
}

-(void)createTableView{
    self.tableView = [[UITableView  alloc] initWithFrame:CGRectMake(0,LL_StatusBarAndNavigationBarHeight+10, ScreenWidth, B_HEIGHT-LL_StatusBarAndNavigationBarHeight-LL_TabbarSafeBottomMargin-10)];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.estimatedRowHeight = 0;
    self.tableView.backgroundColor  = White_Color;
    self.tableView.estimatedSectionFooterHeight = 0;
    self.tableView.estimatedSectionHeaderHeight = 0;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.tableView registerNib:[UINib nibWithNibName:[CommonTableViewCell reuseIdentifier] bundle:nil] forCellReuseIdentifier:[CommonTableViewCell reuseIdentifier]];
    [self.tableView registerNib:[UINib nibWithNibName:[TouXiangTableViewCell reuseIdentifier] bundle:nil] forCellReuseIdentifier:[TouXiangTableViewCell reuseIdentifier]];
    [self.view addSubview:self.tableView];

}

///城市选择器
- (void)chooseAddress {
    CitiesListView *view = [[CitiesListView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight)];
    [[AppDelegate shareDelegete].window addSubview:view];
    WEAKSELF
    [view setPACStr:^(NSString * _Nonnull PACStr, NSString * _Nonnull codeStr, NSString * _Nonnull addressArrStr) {
        NSArray *city = [codeStr componentsSeparatedByString:@","];
        NSArray *cityName = [addressArrStr componentsSeparatedByString:@","];
        self.workAddressStr = [cityName componentsJoinedByString:@""];
        self.workAddress = city.lastObject;
        [self.tableView reloadData];
    }];
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return  self.dataAry.count;
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
     return 1;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.row == 0) {
        TouXiangTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:[TouXiangTableViewCell reuseIdentifier]];
        if (!cell) {
            cell = [[TouXiangTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:[TouXiangTableViewCell reuseIdentifier]];
        }
        [cell.headerButton setBackgroundImageForState:UIControlStateNormal withURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",HTTP_URL,self.info.avatar]] placeholderImage:Image(@"header_default")];
        [cell.headerButton whenTapped:^{
            [self upDateHeaderImage];
        }];
        cell.nameLb.text = self.dataAry[indexPath.row];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        
        return cell;
    } else {
        CommonTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:[CommonTableViewCell reuseIdentifier]];
        if (!cell) {
            cell = [[CommonTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:[CommonTableViewCell reuseIdentifier]];
        }
        cell.nameLb.text = self.dataAry[indexPath.row];
        cell.selectionStyle= UITableViewCellSelectionStyleNone;
        cell.contentTF.userInteractionEnabled = indexPath.row != 3;
        switch (indexPath.row) {
            case 1:
            {
                [ChineseNotificationHelp ChineseNotificationHelpShareWithTextFiled:cell.contentTF];
                if (self.userName.length > 0){
                    cell.contentTF.text = self.userName;
                } else {
                    cell.contentTF.placeholder = @"请输入真实姓名";
                }
            }
            break;
            case 2:
            {
                cell.contentTF.keyboardType=UIKeyboardTypeASCIICapable;
                if (self.carNum.length > 0){
                    cell.contentTF.text = self.carNum;
                } else {
                    cell.contentTF.placeholder = @"请输入身份证号";
                }
            }
            break;
            case 3:
            {
               
                if (self.workAddress.length > 0) {
                    cell.contentTF.text = self.workAddressStr;
                } else {
                    cell.contentTF.placeholder = @"请输入工作地点";
                }
            }
            break;
            default:
            break;
        }
        cell.indexPath = indexPath;
        [cell setCurrentValueBlock:^(NSString * _Nonnull contentString, NSIndexPath * _Nonnull indexPath) {
            if (indexPath.row == 1) {
                self.userName = contentString;
            }else if (indexPath.row == 2){
                self.carNum = contentString;
            } else {
                self.workAddress = contentString;
            }
        }];
        return cell;
    }
   
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.row == 0) {
        return [TouXiangTableViewCell cellHeight];
    } else {
        return [CommonTableViewCell cellHeight];
    }
   
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.row == 3) {
        [self chooseAddress];
    }
}

-(void)createRightButtonItem{
    UIButton *eduitButton = [UIButton buttonWithType:UIButtonTypeCustom];
    eduitButton.frame = CGRectMake(ScreenWidth - 65,  KStatuesBarHeight, 50, 30);
   [eduitButton setTitle:@"保存" forState:UIControlStateNormal];
    eduitButton.titleLabel.font = [UIFont systemFontOfSize:FontSize(13.0)];
     eduitButton.titleLabel.textAlignment = NSTextAlignmentLeft;
    [eduitButton setTitleColor:White_Color forState:UIControlStateNormal];
     eduitButton.backgroundColor = mainColor;
    [eduitButton createBordersWithColor:nil withCornerRadius:5.0 andWidth:0];
    [eduitButton addTarget:self action:@selector(EduitButtonClick) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:eduitButton];
}

-(void)EduitButtonClick{
    [self.view endEditing:YES];
    if (self.userName.length == 0) {
        showAlert(@"请输入真实姓名");
        return;
    }
    if (self.carNum.length == 0) {
        showAlert(@"请输入身份证号");
        return;
    }
    if (![self.carNum isCorrect:self.carNum]){
        showAlert(@"身份证格式不正确");
        return;
    }
    if (self.workAddress.length == 0) {
        showAlert(@"请输入工作地址");
        return;
    }
    
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    [params setObject:@"1" forKey:@"cmd"];
    [params setObject:self.userName forKey:@"realName"];
    [params setObject:self.carNum forKey:@"carNum"];
    [params setObject:self.workAddress forKey:@"workAddress"];
    [self commitUpDateInfo:params];
}

#pragma mark---上传图片
-(void)upDateHeaderImage{
    
    UIAlertController *alertvc = [UIAlertController alertControllerWithTitle:@"上传照片" message:nil preferredStyle:UIAlertControllerStyleActionSheet];
        UIAlertAction *myLibraryAction = [UIAlertAction actionWithTitle:@"从相册选择" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            
            NSInteger sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
            if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0){
                PHAuthorizationStatus status = [PHPhotoLibrary authorizationStatus];
                if (status == PHAuthorizationStatusDenied || status == PHAuthorizationStatusRestricted) {
                    //相册权限受限制
                    showAlert(@"请前往设置-隐私-相机-利行租赁端-允许访问");
                    return;
                }
            }
            UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init];
             imagePickerController.modalPresentationStyle = 0;
            [imagePickerController.navigationBar setTintColor:[UIColor blackColor]];
            imagePickerController.delegate = self;
            imagePickerController.allowsEditing = NO;
            imagePickerController.sourceType = sourceType;
            [self presentViewController:imagePickerController animated:YES completion:^{}];
        }];
        [alertvc addAction:myLibraryAction];
        UIAlertAction *daildAction = [UIAlertAction actionWithTitle:@"拍照上传" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        // 判断是否支持相机
        if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
            
            NSUInteger sourceType = UIImagePickerControllerSourceTypeCamera;

            if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0){
                PHAuthorizationStatus status = [PHPhotoLibrary authorizationStatus];
                if (status == PHAuthorizationStatusDenied || status == PHAuthorizationStatusRestricted) {
                    //相册权限受限制
                    showAlert(@"请前往设置-隐私-相机-利行租赁端-允许访问");
                    return;
                }
            }
            UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init];
             imagePickerController.modalPresentationStyle = 0;
            [imagePickerController.navigationBar setTintColor:[UIColor blackColor]];
            imagePickerController.delegate = self;
            imagePickerController.allowsEditing = NO;
            imagePickerController.sourceType = sourceType;
            [self presentViewController:imagePickerController animated:YES completion:^{}];
        }
        
    }];
    [alertvc addAction:daildAction];
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {

    }];
    [alertvc addAction:cancelAction];
    [self presentViewController:alertvc animated:YES completion:nil];
}

#pragma mark - image picker delegte
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    [picker dismissViewControllerAnimated:YES completion:^{}];
        UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
        NSMutableArray * tmpAry = [NSMutableArray array];
        NSData * data = [image compressMidQualityWithLengthLimit:kPhotoFileSize];
        UIImage * img0 = [UIImage imageWithData:data];
        YLUploadMedia * imageM = [YLUploadMedia mediaWithType:YLUploadMediaTypeJpg mediaName:nil mimeName:@"file" obj:img0];
        [tmpAry addObject:imageM];
        NSLog(@"<<-- 原尺寸:%@  新尺寸:%@  大小:%.4fMB -->>", NSStringFromCGSize(image.size), NSStringFromCGSize(img0.size),(double)data.length / 1024.0f / 1024.0f);
         [self shanChuanImageWithArray:tmpAry ];
}

///上传头像
-(void)shanChuanImageWithArray:(NSMutableArray *)tmpAry{
    
    
    [MSNetworkManager postRevertUrl:POST_UploadFile_URL params:@{@"type":@"1"} formData:tmpAry success:^(id  _Nonnull paginationObj, id  _Nonnull resonseObj, BOOL isSuccess, NSString * _Nonnull message) {
        
        self.avatar = resonseObj[@"url"];
        NSMutableDictionary *params = [NSMutableDictionary dictionary];
        [params setObject:self.avatar forKey:@"avatar"];
        [params setObject:@"1" forKey:@"cmd"];
        [self commitUpDateInfo:params];
        
    } failure:^(NSUInteger code, NSString * _Nonnull message) {
    } withShowHud:YES];
    
    
}

///修改个人信息
-(void)commitUpDateInfo:(NSMutableDictionary *)params{
    
    
    [MSNetworkManager postRevertUrl:Post_UpDateUserInfo params:params success:^(id  _Nonnull paginationObj, id  _Nonnull resonseObj, BOOL isSuccess, NSString * _Nonnull message) {
        
        if (isSuccess) {
            showAlert(@"设置成功");
            [self refrefhUI];
            
            [self getUserInfo:^(BOOL isSuccess) {}];
            
            
        }
       
        
    } failure:^(NSUInteger code, NSString * _Nonnull message) {
    } withShowHud:YES];
    


}

-(void)refrefhUI
{
    self.info = [YLUserMgr fetchUser];
    if (self.info.realName.length > 0) {
        self.userName = self.info.realName;
    }
    if (self.info.carNum.length > 0) {
        self.carNum = self.info.carNum;
    }
    if (self.info.workAddress.length > 0){
        self.workAddressStr = self.info.workAddressStr;
        self.workAddress = self.info.workAddress;
    }
    if (self.info.logoUrl.length>0){
        self.avatar = self.info.avatar;
    }
    [self.tableView reloadData];
}

@end
